/**
 * 
 */
package com.shine.icis.blo.imp;

import java.util.List;

import com.shine.icis.blo.IFlowService;
import com.shine.icis.blo.ISubmitTaskService;
import com.shine.icis.dao.ISubmitReportDAO;
import com.shine.icis.hbean.SubmitReport;
import com.shine.icis.hbean.TaskIns;
/**
 * @author zsy
 *
 */
public class SubmitTaskService implements ISubmitTaskService {
	
	private ISubmitReportDAO submitReportDAO;
	private IFlowService flowService;

	public void setSubmitReportDAO(ISubmitReportDAO submitReportDAO) {
		this.submitReportDAO = submitReportDAO;
	}

	public void setFlowService(IFlowService flowService) {
		this.flowService = flowService;
	}

	@Override
	public SubmitReport getSubmitReportById(String id) {
		return submitReportDAO.findById(id);
	}

	@Override
	public void txDealApproveTask(String taskId, String comment, boolean passed, String userCode) throws Exception{
		if (taskId == null) {
			throw new IllegalArgumentException();
		}
		TaskIns ti = flowService.txEndTask(taskId, userCode, comment);
		
		SubmitReport sr = submitReportDAO.findByInsId(ti.getFlowIns().getInsId());
		
//		if (passed) {
			flowService.txToNextNode(sr.getInsId(), !passed);//转到下一步
//		} else {
//			//后期可能要改为重回第一步
//			flowService.txForceEndFlowIns(sr.getInsId());//强制结束
//		}
	}
	
	@Override
	public void txCancelTask(String taskId, String comment, String userCode) throws Exception {
		if (taskId == null) {
			throw new IllegalArgumentException();
		}
		TaskIns ti = flowService.txEndTask(taskId, userCode, comment);
		SubmitReport sr = submitReportDAO.findByInsId(ti.getFlowIns().getInsId());
		sr.setPassed(false);
		submitReportDAO.update(sr);
		flowService.txForceEndFlowIns(ti.getFlowIns().getInsId());
	}
	
	
	@Override
	public void txArchiveSubmitReport(String flowInsId) {
		SubmitReport sr = submitReportDAO.findByInsId(flowInsId);
		if(sr != null) {
			sr.setPassed(true);
			submitReportDAO.update(sr);
		}
	}
	
	
	
	
	
	
	@Override
	public SubmitReport getLastSubmitReport(String userCode) {
		List<TaskIns> tis = flowService.getTasks(userCode, null);
		if (tis == null || tis.isEmpty()) {
			return null;
		}
		TaskIns ti = tis.get(0);
		
		if (ti == null || ti.getTaskStatus() == TaskIns.TASK_STATUS_END) {
			return null;
		}
		
		SubmitReport sr = submitReportDAO.findByInsId(ti.getFlowIns().getInsId());
		if (sr != null) {
			sr.setTaskId(ti.getTaskId());
		}
		return sr;
	}
}
